import React, { useState, useEffect } from "react";
import { Link, useNavigate, useSearchParams } from "react-router-dom";
import Navbar from "../Navbar.jsx";
import Sidebar from "../Sidebar.jsx";
import axios from "axios";
import { FaTachometerAlt } from "react-icons/fa";
import Select from "react-select";
import LoadingScreen from "../../Loading.jsx";

const CouponForm = () => {
  const navigate = useNavigate();
  const [customers, setCustomers] = useState([]);
  const [discountCoupons, setDiscountCoupons] = useState([]);
  const [isSidebarOpen, setSidebarOpen] = useState(true);
  const [loading, setLoading] = useState(false);
  const [searchParams] = useSearchParams();
  const couponid = searchParams.get("couponid");
  const [generatedCode, setGeneratedCode] = useState("");

  const [formData, setFormData] = useState({
    customerData: null,
    appCustomer: null,
    discountCoupon: null,
    couponCode: "",
    couponType: "",
    description: "",
    expiryDate: "",
    occasionName: "",
    value: 0,
    usedDate: new Date().toISOString(),
  });

  const couponTypeOptions = [
    { label: "Percentage(%)", value: "percentage" },
    { label: "Fixed", value: "fixed" },
    { label: "Value", value: "value" },
  ];

  useEffect(() => {
    if (window.innerWidth < 768) {
      setSidebarOpen(false);
    }
  }, []);

  const fetchCustomers = async () => {
    try {
      setLoading(true);
      const adminCustomersResponse = await axios.get("https://mybackend-l7om.onrender.com/api/customer-data/all", {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });
      const adminCustomers = adminCustomersResponse.data.map((item) => ({
        label: `Admin: ${item.customerName}`,
        value: item._id,
        source: "customerData",
      }));

      const appCustomersResponse = await axios.get("https://mybackend-l7om.onrender.com/customer/customers", {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });
      const appCustomers = appCustomersResponse.data.data.map((item) => ({
        label: `App: ${item.name || item.phone}`,
        value: item._id,
        source: "appCustomer",
      }));

      setCustomers([...adminCustomers, ...appCustomers]);
    } catch (err) {
      console.log(err.message);
    } finally {
      setLoading(false);
    }
  };

  const fetchDiscountCoupons = async () => {
    try {
      setLoading(true);
      const response = await axios.get("https://mybackend-l7om.onrender.com/api/discount-coupons", {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });
      if (response.data) {
        const discountOptions = response.data.map((coupon) => ({
          label: coupon.occasionName,
          value: coupon._id,
          couponValue: coupon.value, // Renamed to avoid conflict
          couponType: coupon.couponType,
          expiryDate: coupon.expiryDate ? new Date(coupon.expiryDate).toISOString().split("T")[0] : "",
        }));
        setDiscountCoupons(discountOptions);
      }
    } catch (err) {
      console.log(err.message);
    } finally {
      setLoading(false);
    }
  };

  const fetchCustomerCoupon = async () => {
    if (!couponid) return;
    try {
      setLoading(true);
      const response = await axios.get(`https://mybackend-l7om.onrender.com/api/customer-coupons/${couponid}`, {
        headers: { Authorization: `Bearer ${localStorage.getItem("token")}` },
      });
      if (response.data) {
        setFormData({
          customerData: response.data.customerData?._id || response.data.customerData || null,
          appCustomer: response.data.appCustomer?._id || response.data.appCustomer || null,
          discountCoupon: response.data.discountCoupon?._id || response.data.discountCoupon || null,
          couponCode: response.data.couponCode || "",
          couponType: response.data.couponType || "",
          description: response.data.description || "",
          expiryDate: response.data.expiryDate ? new Date(response.data.expiryDate).toISOString().split("T")[0] : "",
          occasionName: response.data.occasionName || "",
          value: response.data.value || 0,
          usedDate: response.data.usedDate || new Date().toISOString(),
        });
      }
    } catch (err) {
      console.log(err.message);
    } finally {
      setLoading(false);
    }
  };

  const createCustomerCoupon = async () => {
    try {
      setLoading(true);
      const selectedCustomer = customers.find((c) => c.value === (formData.customerData || formData.appCustomer));
      const payload = {
        customerData: selectedCustomer?.source === "customerData" ? selectedCustomer.value : undefined,
        appCustomer: selectedCustomer?.source === "appCustomer" ? selectedCustomer.value : undefined,
        discountCoupon: formData.discountCoupon,
        couponCode: formData.couponCode,
        usedDate: formData.usedDate,
        status: "Active",
        occasionName: formData.occasionName,
        expiryDate: formData.expiryDate,
        value: formData.value,
        couponType: formData.couponType,
        description: formData.description,
      };
      const response = await axios.post("https://mybackend-l7om.onrender.com/api/customer-coupons", payload, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      alert("Customer coupon added successfully");
      navigate("/customer-coupen-list");
    } catch (err) {
      alert("Unable to add customer coupon");
      console.log(err.message);
    } finally {
      setLoading(false);
      setFormData({
        customerData: null,
        appCustomer: null,
        discountCoupon: null,
        couponCode: "",
        couponType: "",
        description: "",
        expiryDate: "",
        occasionName: "",
        value: 0,
        usedDate: new Date().toISOString(),
      });
    }
  };

  const updateCustomerCoupon = async () => {
    try {
      setLoading(true);
      const selectedCustomer = customers.find((c) => c.value === (formData.customerData || formData.appCustomer));
      const payload = {
        customerData: selectedCustomer?.source === "customerData" ? selectedCustomer.value : undefined,
        appCustomer: selectedCustomer?.source === "appCustomer" ? selectedCustomer.value : undefined,
        discountCoupon: formData.discountCoupon,
        couponCode: formData.couponCode,
        usedDate: formData.usedDate,
        status: "Active",
        occasionName: formData.occasionName,
        expiryDate: formData.expiryDate,
        value: formData.value,
        couponType: formData.couponType,
        description: formData.description,
      };
      const response = await axios.put(`https://mybackend-l7om.onrender.com/api/customer-coupons/${couponid}`, payload, {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${localStorage.getItem("token")}`,
        },
      });
      alert("Customer coupon updated successfully");
      navigate("/customer-coupen-list");
    } catch (err) {
      alert("Unable to update customer coupon");
      console.log(err.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    const fetchData = async () => {
      await fetchCustomers();
      await fetchDiscountCoupons();
      if (couponid) {
        await fetchCustomerCoupon();
      }
    };
    fetchData();
  }, []);

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData((prev) => ({
      ...prev,
      [name]: e.target.type === "number" ? Number(value) : value,
    }));
  };

  const handleCustomerChange = (selectedOption) => {
    if (!selectedOption) {
      setFormData((prev) => ({
        ...prev,
        customerData: null,
        appCustomer: null,
      }));
      return;
    }

    setFormData((prev) => ({
      ...prev,
      customerData: selectedOption.source === "customerData" ? selectedOption.value : null,
      appCustomer: selectedOption.source === "appCustomer" ? selectedOption.value : null,
    }));
  };

  const handleDiscountCouponChange = (selectedOption) => {
    if (!selectedOption) {
      setFormData((prev) => ({
        ...prev,
        discountCoupon: null,
        value: 0,
        couponType: "",
        expiryDate: "",
      }));
      return;
    }
    setFormData((prev) => ({
      ...prev,
      discountCoupon: selectedOption.value,
      value: selectedOption.couponValue || 0,
      couponType: selectedOption.couponType || "",
      expiryDate: selectedOption.expiryDate || "",
    }));
  };

  const generateCouponCode = () => {
    const code = `CUP-${Date.now().toString(36).substr(-6).toUpperCase()}`;
    setFormData((prev) => ({ ...prev, couponCode: code }));
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (couponid) {
      updateCustomerCoupon();
      return;
    }
    createCustomerCoupon();
  };

  if (loading) return <LoadingScreen />;

  return (
    <div className="flex flex-col h-screen">
      <Navbar isSidebarOpen={isSidebarOpen} setSidebarOpen={setSidebarOpen} />
      <div className="flex flex-grow">
        <Sidebar isSidebarOpen={isSidebarOpen} />
        <div className={`flex-grow p-4 min-h-screen transition-all duration-300 ${isSidebarOpen ? "ml-64" : "ml-0"}`}>
          <header className="flex flex-col items-center justify-between h-auto p-4 mb-6 bg-gray-100 rounded-lg shadow-md md:flex-row">
            <h1 className="text-2xl font-semibold">Add/Update Customer Coupon</h1>
            <div className="flex items-center space-x-2 text-blue-600">
              <Link to="/" className="flex items-center text-sm text-gray-500 no-underline hover:text-cyan-600">
                <FaTachometerAlt className="mr-2 text-gray-500 hover:text-cyan-600" /> Home
              </Link>
              <span className="text-gray-400">{">"}</span>
              <Link to="/customer-coupons" className="text-sm text-gray-500 no-underline hover:text-cyan-600">
                Customer Coupons
              </Link>
            </div>
          </header>
          <form className="flex flex-col p-4 space-y-4 bg-white border-t-4 rounded-lg shadow-md border-cyan-500" onSubmit={handleSubmit}>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">
                Customer Name <span className="text-red-500">*</span>
              </label>
              <div className="w-2/3">
                <Select
                  options={customers}
                  onChange={handleCustomerChange}
                  value={
                    customers?.find((option) => 
                      option.value === (formData.customerData || formData.appCustomer)
                    ) || null
                  }
                  placeholder="Select Customer"
                  noOptionsMessage={() => "No Records Found"}
                />
              </div>
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">
                Discount Coupon <span className="text-red-500">*</span>
              </label>
              <div className="w-2/3">
                <Select
                  options={discountCoupons}
                  onChange={handleDiscountCouponChange}
                  value={discountCoupons?.find((option) => option.value === formData.discountCoupon) || null}
                  placeholder="Select Discount Coupon"
                  noOptionsMessage={() => "No Records Found"}
                />
              </div>
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">
                Coupon Code <span className="text-red-500">*</span>
              </label>
              <div className="w-2/3 flex items-center">
                <input
                  type="text"
                  className="w-full p-2 border rounded focus:ring focus:ring-blue-300"
                  name="couponCode"
                  value={formData.couponCode}
                  onChange={handleChange}
                  placeholder="Enter or generate coupon code"
                />
                <button
                  type="button"
                  className="ml-2 px-2 py-1 text-white bg-blue-500 rounded hover:bg-blue-600"
                  onClick={generateCouponCode}
                >
                  Generate
                </button>
              </div>
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">Expire Date</label>
              <input
                type="date"
                className="w-2/3 p-2 border rounded focus:ring focus:ring-blue-300 bg-gray-100"
                name="expiryDate"
                value={formData.expiryDate}
                onChange={handleChange}
                readOnly
              />
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">Coupon Value</label>
              <input
                type="number"
                className="w-2/3 p-2 border rounded focus:ring focus:ring-blue-300 bg-gray-100"
                name="value"
                value={formData.value}
                onChange={handleChange}
                readOnly
                min="0"
                placeholder=""
              />
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">Coupon Type</label>
              <div className="w-2/3">
                <Select
                  options={couponTypeOptions}
                  value={couponTypeOptions?.find((option) => option.value === formData.couponType) || null}
                  placeholder={formData.couponType || "-Select-"}
                  isDisabled={true}
                />
              </div>
            </div>
            <div className="flex items-center gap-4">
              <label className="w-1/3 text-sm font-medium text-right">Description</label>
              <textarea
                className="w-2/3 p-2 border rounded focus:ring focus:ring-blue-300"
                name="description"
                value={formData.description}
                onChange={handleChange}
                placeholder=""
              ></textarea>
            </div>
            <div className="flex justify-end gap-4 mt-4">
              <button type="submit" className="px-6 py-2 font-medium text-white transition bg-green-600 rounded hover:bg-green-700">
                Save
              </button>
              <button
                type="button"
                className="px-6 py-2 font-medium text-white transition bg-yellow-500 rounded hover:bg-yellow-600"
                onClick={() => navigate("/customer-coupen-list")}
              >
                Close
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
};

export default CouponForm;